package com.yy.hi.library.hilog;

/**
 * User: gongyongfeng2@yy.com
 * Date: 2020/6/11 17 :03
 */
public class HiStackTraceUtil {

    public static StackTraceElement[] getCropRealStackTrace(StackTraceElement[] stackTrace,
                                                     String ignorePackage, int maxDepath) {
        return cropStackTrace(getRealStackTrace(stackTrace, ignorePackage), maxDepath);
    }

    private static StackTraceElement[] getRealStackTrace(StackTraceElement[] stackTraceElements,
                                                         String ignorePackage) {
        int ignoreDepth = 0;
        int allDepth = stackTraceElements.length;
        String className;
        for (int i = allDepth - 1; i > 0; i--) {
            className = stackTraceElements[i].getClassName();
            if (ignorePackage != null && className.startsWith(ignorePackage)) {
                ignoreDepth = i + 1;
                break;
            }
        }

        int realDepth = allDepth - ignoreDepth;
        StackTraceElement[] realStacks = new StackTraceElement[realDepth];
        System.arraycopy(stackTraceElements, ignoreDepth, realStacks, 0, realDepth);
        return realStacks;
    }

    private static StackTraceElement[] cropStackTrace(StackTraceElement[] elements, int maxDepth) {
        int realDepth = elements.length;
        if (maxDepth > 0) {
            realDepth = Math.min(realDepth, maxDepth);
        }
        StackTraceElement[] realStackTraces = new StackTraceElement[realDepth];
        System.arraycopy(elements, 0, realStackTraces, 0, realDepth);
        return realStackTraces;
    }
}
